package com.yangye.pidoublename.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/25
 */
@Service
public class HeiLongJiangServiceImpl implements DoubleNameService {

	private final String QUERY_URL = "http://gafw.hljga.gov.cn/wyc.do?method=earchChongming";

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("name", name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params, httpHeaders);
		String result = restTemplate.postForObject(QUERY_URL, request, String.class);
		JSONArray array = JSON.parseArray(result);
		Integer man = 0;
		Integer woman = 0;
		for (Object o : array) {
			JSONObject jsonObject = JSON.parseObject(o.toString());
			if (!CollectionUtils.isEmpty(jsonObject)) {
				// 男
				if (jsonObject.getInteger("XB") == 1) {
					man = jsonObject.getInteger("ZS");
				}
				// 女
				if (jsonObject.getInteger("XB") == 2) {
					woman = jsonObject.getInteger("ZS");
				}
			}
		}
		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setProvince(ProvinceEnum.HEILONGJIANG.getName());
		doubleNameVo.setName(name);
		doubleNameVo.setMan(man);
		doubleNameVo.setWoman(woman);
		doubleNameVo.setTotal(man + woman);
		return doubleNameVo;
	}
}
